package com.lianyu507.task;

import com.alibaba.fastjson.JSONObject;
import com.lianyu507.pojo.CrArticle;
import com.lianyu507.pojo.CrArticleExample;
import com.lianyu507.service.CrArticleService;
import com.lianyu507.service.TranslateService;
import com.lianyu507.util.DateUtil;
import com.lianyu507.util.HttpClientUtil;
import com.lianyu507.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * =================================
 * <p>
 * Created by sun cai li on 2017/11/21.
 * <p>
 * 描述:
 */

@Component
public class CrawlerTask {
    @Autowired
    private CrArticleService crArticleService;
    @Autowired
    private TranslateService translateService;


    @Scheduled(cron = "0 0 22 * * ?")
    public boolean crawArticle() {


        //get current month string eg: 2017-11
        String date = DateUtil.getyyyy_MM(new Date());
        String json = HttpClientUtil.doGet("https://www.nationalgeographic.com/content/photography/en_US/photo-of-the-day/_jcr_content/.gallery." + date + ".json");
        //http client to get json
        JSONObject jsonToPojo = JsonUtils.jsonToPojo(json, JSONObject.class);
        List<Map<String, String>> items = (List<Map<String, String>>) jsonToPojo.get("items");
        for (int i = 0; i < items.size(); i++) {
            Map<String, String> item = items.get(i);
            CrArticle crArticle = new CrArticle();
            crArticle.setTitle(jsonToPojo.get("galleryTitle").toString());
            crArticle.setPictureTitle(item.get("title"));
            crArticle.setAuthor(item.get("credit"));
            crArticle.setPictureDes(item.get("caption"));
            crArticle.setId((int) (Math.random() * 10000));
            crArticle.setStatus((byte) 1);
            crArticle.setArticleContent("");
            crArticle.setPictureUrl("url" + "originalUrl");
            crArticle.setCreateTime(new Date());
            crArticle.setUpdateTime(new Date());
            CrArticleExample example = new CrArticleExample();
            CrArticleExample.Criteria criteria = example.createCriteria().andPictureTitleEqualTo(item.get("title"));
            List<CrArticle> list = crArticleService.selectByExample(example);
            if (list.size()==0) {
                crArticleService.insert(crArticle);
            } else {
                break;
            }
        }
        return true;
    }
}

